package com.api.devices.test;

import java.io.*;

public class IntelHexFileReader {
    private static String filePath = "D:\\Project\\demo\\20250515210200.dat";
    public static void main(String[] args) {
//        String filePath = "data.dat";

        try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
//            try{
//                BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(filePath), "UTF-8"));
            // 跳过第一行（通常是文件头）
            br.readLine();

            String line;
            while ((line = br.readLine()) != null) {
                if (line.startsWith(":")) {
                    // 解析Intel HEX记录
                    HexRecord record = parseIntelHexRecord(line);

                    // 处理记录
                    System.out.println("Record type: " + record.recordType);
                    System.out.println("Address: 0x" + Integer.toHexString(record.address));
                    System.out.println("Data: " + bytesToHex(record.data));
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static class HexRecord {
        int byteCount;
        int address;
        int recordType;
        byte[] data;
        int checksum;
    }

    private static HexRecord parseIntelHexRecord(String line) {
        HexRecord record = new HexRecord();

        // 去掉起始冒号
        String hexData = line.substring(1);

        // 解析记录
        record.byteCount = Integer.parseInt(hexData.substring(0, 2), 16);
        record.address = Integer.parseInt(hexData.substring(2, 6), 16);
        record.recordType = Integer.parseInt(hexData.substring(6, 8), 16);
//        record.byteCount = Integer.parseInt(hexData.substring(0, 4), 32);
//        record.address = Integer.parseInt(hexData.substring(4, 6), 16);
//        record.recordType = Integer.parseInt(hexData.substring(6, 8), 16);

        // 解析数据
        int dataLength = record.byteCount * 2;
        record.data = hexStringToBytes(hexData.substring(8, 8 + dataLength));

        // 解析校验和
        record.checksum = Integer.parseInt(hexData.substring(8 + dataLength), 16);

        return record;
    }

    private static String bytesToHex(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        for (byte b : bytes) {
            sb.append(String.format("%02X ", b));
        }
        return sb.toString();
    }

    private static byte[] hexStringToBytes(String hexString) {
        // 同上例中的实现
        System.out.println("hexStringToBytes:"+ hexString);
        return null;
    }
}